<script setup lang="ts">
import { ref, onMounted } from "vue";
import request from "@/utils/request";
const query = ref("");
const booksList = ref([]);
const queryHistory = ref([]);

const searchQuery = async () => {
  const result = await request({
    url: `search/${query.value}`,
  });
  saveSearchHistory();
  booksList.value = result;
  console.log(result, "result-----搜索", booksList.value);
};
// 获取搜索历史
const getSearchHistory = async () => {
  const history = uni.getStorageSync("searchHistory") || [];
  queryHistory.value = history;
};
onMounted(() => {
  getSearchHistory();
});
// 保存搜索历史
const saveSearchHistory = () => {
  const history = uni.getStorageSync("searchHistory") || [];
  const index = history.indexOf(query.value);
  if (index !== -1) {
    history.splice(index, 1);
  }
  history.unshift(query.value);
  queryHistory.value = history;
  uni.setStorageSync("searchHistory", history);
};
const removeHistory = () => {
  uni.removeStorageSync("searchHistory");
  queryHistory.value = [];
};

const handleClick = (item) => {
  query.value = item;
  searchQuery();
};

const handleReturnClick = () => {
  uni.navigateBack();
};
const cancel = () => {
  query.value = "";
  booksList.value = [];
};
</script>

<template>
  <div class="w-100% search">
    <i @click="handleReturnClick('')" class="i-carbon:arrow-left"></i>
    <div class="flex-1">
      <uni-search-bar
        radius="5"
        v-model="query"
        placeholder="请输入书名或作则"
        clearButton="auto"
        cancelButton="auto"
        @confirm="searchQuery"
        @cancel="cancel"
      ></uni-search-bar>
    </div>
  </div>
  <div v-if="booksList.length > 0">
    <scroll-view scroll-y="true">
      <template v-for="item in booksList" :key="item.id">
        <BooksItem :item="item"></BooksItem>
      </template>
    </scroll-view>
  </div>
  <div v-else>
    <div class="flex justify-between px-1 pt-2">
      搜索记录 <i @click="removeHistory" class="i-ep:delete"></i>
    </div>
    <div classs="flex flex-wrap justify-flex-start mt-20RPX p-10rpx">
      <uni-tag
        class="mr-2"
        @click="handleClick(item)"
        v-for="item in queryHistory"
        :key="item"
        :text="item"
        type="primary"
      />
    </div>
  </div>
</template>
<route lang="json">
{
  "layout": false
}
</route>
<style scoped lang="scss">
.search {
  width: 100%;
  display: flex;
  align-items: center;
}
</style>
